var Tasklog=Tasklog||{}
Tasklog.Tags=(function(Tasklog){ return { 
	tags: null, activeTagEl:null, activeTag:null, showTagNames: true, bgPicker:null, colPicker:null
	,init: function(el){
		var self=this;
		$(el).click(function(ev){ self.onClick($(this),ev.target); ev.stopPropagation(); })
	}
	
	,onClick: function(el,target){
		if (el.hasClass('tag-expanded')){
			if (target.className=='close'){ this.remove(el); return; }
			el.removeClass('tag-expanded');
			var w=$('span:first-child',el).outerWidth()
			w=this.showTagNames?w:14
			el.animate({width:w},{duration:'fast'});
		} 
		else {
			el.width('auto');
			el.addClass('tag-expanded');
			var w=el.outerWidth(), tw=$('span:first-child',el).outerWidth()
			el.width(this.showTagNames?tw:14);
			el.animate({width:w},{duration:'fast'});			
		}
	}
	
	,collapseAll: function(){var self=this; $('.tag-expanded').each(function(){$(this).removeClass('tag-expanded').width(self.showTagNames?'auto':14)})}
	
	,drawMenu: function(){
		var tags=this.getTags();
		if (!tags) return;
		var tlen=tags.length, tagItems=new Array();
		$('#tagmenu li:not(.menu-tag-manager)').remove();
		for (var t=0; t<tlen; t++){
			var name=tags[t].name, id=tags[t].id, style='background-color:'+tags[t].bg+';color:'+tags[t].color+';';
			tagItems.push('<li onclick="tagTask('+id+',\''+name+'\', \''+style+'\')"><span class="menutag" style="'+style+'"></span>'+name+'</li>')
		}
		tagItems.push('<li class="separator"></li>')
		if (tagItems.length) $('#tagmenu').prepend(tagItems.join(''));
		
		var style=this.showTagNames?'':'.tag{width:14px}.tag span{display:none}.tag-expanded span,.tag-expanded span.close{display:block;}'
		$('#dynamicCSS').append(style);
	}
	
	,taskTags: function(tagStr){
		if (!tagStr.length) return'';
		var tags=tagStr.split(','), tlen=tags.length, i, tagsHtml='';
		for (i=0; i<tlen; i++) if (tags[i].length){
			var tag=this.getTagById(tags[i]);
			if (tag) tagsHtml+='<em title="'+tag.name+'" class="tag" style="'+tag.style+'"><span>'+tag.name+'</span><span class="close" title="Remove">x</span></em>';
		} 
		return tagsHtml;	
	}
	
	,rewriteTaskTags: function(){
		var tasks=Tasklog.DB.getAll(), rows=$('.task-table .task'), rlen=rows.length;
		for(var i=0; i<rlen; i++){
			var row=$(rows[i]), cont=$('.task-description',row);
			var id=row[0].id;
			if (id){
				var task=Tasklog.DB.getTaskById(id), taskTags=Tasklog.Tags.taskTags(task.tags)
				cont.find('em.tag').remove();
				cont.prepend(taskTags)		
			} 
		}	
	}
	
	,add: function(id,label,style){ // add task tag
		var row=$('table.task-table tr.task-edit'), tags=row.find('.task-description em'), tlen=tags.length, i
		if (!row.length) return;
		for(i=0; i<tlen; i++) if(tags[i].title==label){ this.remove($(tags[i])); return; }				
		var tag=$('<em class="tag tag-expanded" title="'+label+'" style="display:none;'+style+'"><span>'+label+'</span><span class="close" title="Remove">x</span></em>');
		$('.task-description',row).prepend(tag)
		tag.show('fast',this.init(tag));
		Tasklog.DB.addTaskTag(id+'',row[0].id);
	}
	
	,remove: function(el){ // remove task tag
		var self=this;
		el.hide('fast',function(){
			var taskID=el.parents('.task')[0].id, tag=el[0].title;
			tag=self.getTagByName(tag);
			Tasklog.DB.removeTaskTag(tag+'',taskID);
			el.remove()
		});
	}
	
	,getTags: function(reread){
		if(!this.tags) this.tags=[];
		if(!this.tags.length || reread) this.tags=Tasklog.DB.getTags();
		if(!this.tags) this.tags=[];
		return this.tags; 
	}

	,getTagByName: function(name){
		var tags=this.getTags(), tlen=tags.length, i;
		for (i=0; i<tlen; i++) if (tags[i].name==name)return tags[i].id; 
	}
		
	,getTagById: function(id){
		var tags=this.getTags(), tlen=tags.length, i;
		for (i=0; i<tlen; i++) if (tags[i].id==id){ 
			tags[i].style='background-color:'+tags[i].bg+';color:'+tags[i].color+';'; 
			return tags[i]; 
		} 
	}
	
	
	//*** TAG Manager **************
	,addTag: function(){ 
		var nt=$('<li class="active" title="noname" onclick="editTag(0, this)"><span style="background-color: #666666; color: #F3F3F3;" class="menutag">tag</span>noname</li>');
		$('#tagList ul').prepend(nt)
		this.editTag(0,nt);
	}
	
	,removeTag: function(){
		if (!this.activeTagEl) return;
		var id=this.activeTag.id;
		if (id) Tasklog.DB.removeTag(id);
		this.activeTagEl.remove();
		this.activeTagEl=null;
		$('#tagNameInput').val('')
	}
	
	,saveTag: function(){ 
		if (!this.activeTagEl) return;
		var name=$('#tagNameInput').val(), id=this.activeTag.id, bg=this.activeTag.bg, color=this.activeTag.color;
		this.activeTag.name=name;
		var rec=this.activeTag; delete(rec.style)
		if (!id) id=Tasklog.DB.addTag(rec);
		else Tasklog.DB.updateTag(rec);
		this.getTags(true); // reread tags
		this.drawMenu();
		this.rewriteTaskTags();
		
		var nt=$('<li class="active" title="'+name+'" onclick="editTag('+id+', this)"><span style="background-color:'+bg+'; color:'+color+';" class="menutag">tag</span>'+name+'</li>');
		this.activeTagEl.replaceWith(nt);
		$('#tagNameInput').effect("highlight", {color:'#B45F06'}, 500);
		this.editTag(id,nt);

	}	
	
	,editTag: function(id, tagEl){
		this.activeTagEl=$(tagEl); 
		if (id) this.activeTag=this.getTagById(id); else this.activeTag={color:'#F3F3F3', bg:'#666666'}; //new tag 
		var inp=$('#tagNameInput'), name=this.activeTagEl[0].title;
		this.activeTagEl.siblings('li').removeClass('active'); 
		this.activeTagEl.addClass('active');

		this.colPicker.setColor(this.activeTag.color);
		this.bgPicker.setColor(this.activeTag.bg);
		
		inp.val(name)
		inp.select().focus();
	}
	
	,editTagBG: function(color){
		if (!this.activeTagEl) return;
		$('.menutag',this.activeTagEl).css('backgroundColor',color);
		this.activeTag.bg=color;
	}
	,editTagColor: function(color){
		if (!this.activeTagEl) return;
		$('.menutag',this.activeTagEl).css('color',color);
		this.activeTag.color=color;
	}
	
	,tagManager: function(){
		var tags=this.getTags(), tlen=tags.length||0, tagItems=new Array();
		this.activeTagEl=null;
		this.activeTag=null;
		
		for (var t=0; t<tlen; t++){
			var name=tags[t].name, id=tags[t].id, style='background-color:'+tags[t].bg+';color:'+tags[t].color+';';
			tagItems.push('<li title="'+name+'" onclick="editTag('+id+', this)"><span class="menutag" style="'+style+'">tag</span>'+name+'</li>')
		} 
		
		var cnt='<table id="tagManager">'+
				'<tr class="toolbars"><td>'+
					'<span class="button button-left mn-add" title="Add" onclick="addTag()"><span title="Add">Add</span></span>'+
					'<span class="button button-right mn-del" title="Remove" onclick="removeTag()"><span title="Remove">Remove</span></span>'+
				'</td><td>'+
					'<input type="text" id="tagNameInput">'+
					'<span class="button button-right notext mn-ok" title="Save" onclick="saveTag()"><span title="Save">Save</span></span>'+
				'</td></tr></thead>'+
				'<tr>'+
					'<td id="tagList"><ul>'+tagItems.join('')+'</ul></td>'+
					'<td class="tag-properties"><h3>Background color</h3><div class="cpContainer bgcolor"></div></td>'+
					'<td class="tag-properties"><h3>Text color</h3><div class="cpContainer txtcolor"></div></td>'+
				'</tr>'+
			'</table>';
		
		Tasklog.Window.show(cnt,'Tag Manager', true);
		this.bgPicker=new Tasklog.Colorpicker({ target: $('#tagManager .tag-properties .bgcolor'), defaultColor: 2, scope: this, callback: this.editTagBG  })
		this.colPicker=new Tasklog.Colorpicker({ target: $('#tagManager .tag-properties .txtcolor'), defaultColor: 6, scope: this, callback: this.editTagColor  })
		Tasklog.Window.center();
	}
	
}})(Tasklog);

function addTag(){ Tasklog.Tags.addTag()}
function removeTag(){ Tasklog.Tags.removeTag()}
function editTag(id,el){ Tasklog.Tags.editTag(id,el)}
function saveTag(){ Tasklog.Tags.saveTag()}

function tagTask(id,label,style){ Tasklog.Tags.add(id,label,style) }
function tagManager(){ Tasklog.Tags.tagManager()}
